package com.netty.pro.netty.groupChat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.cache.annotation.CachePut;

/**
 * @author xuzn
 * @ClassName: GroupChatServer
 * @ProjectName netty-pro
 * @date 2020/3/15/9:53
 */
public class GroupChatServer {
  private int port;

  public GroupChatServer(int port) {
    this.port = port;
  }

  // run方法处理客户端请求
  public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(8);
    try {
      ServerBootstrap serverBootstrap = new ServerBootstrap();
      serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
              .option(ChannelOption.SO_BACKLOG, 1024)
              .childOption(ChannelOption.SO_KEEPALIVE, true)
              .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                  ChannelPipeline pipeline = ch.pipeline();
                  // 向pipeline加入一个解码器
                  pipeline.addLast("decoder", new StringDecoder());
                  // 加入一个编码器
                  pipeline.addLast("encoder", new StringEncoder());
                  // 加入自己的handler
                  pipeline.addLast(new GroupChatServerHandler());
                }
              });
      System.out.println("netty服务器启动~~");
      ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
      channelFuture.channel().closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }

  public static void main(String[] args) throws Exception {
    new GroupChatServer(7000).run();
  }
}
